package res

import (
	"encoding/json"
	"net/http"
	"time"
)

type response struct {
	Code    int         `json:"errorCode"`
	Message interface{} `json:"errorMessage,omitempty"`
	Data    interface{} `json:"data,omitempty"`
}

func (c *response) Render(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if e, ok := c.Message.(error); ok {
		c.Message = e.Error()
	}
	if e, ok := c.Data.(error); ok {
		c.Data = e.Error()
	}
	bt, _ := json.Marshal(c)
	_, _ = w.Write(bt)
}

func Success(w http.ResponseWriter, data interface{}) {
	(&response{
		0,
		nil,
		data,
	}).Render(w)
}
func Bad(w http.ResponseWriter, data interface{}) {
	(&response{
		400,
		data,
		nil,
	}).Render(w)
}

func Error(w http.ResponseWriter, data interface{}) {
	(&response{
		500,
		data,
		nil,
	}).Render(w)
}

func Auth(w http.ResponseWriter) {
	(&response{
		401,
		"您还没有登陆",
		nil,
	}).Render(w)
}
func NotFound(w http.ResponseWriter) {
	(&response{
		404,
		"请求路径未找到",
		nil,
	}).Render(w)
}
func NotAllowed(w http.ResponseWriter) {
	(&response{
		405,
		"请求方式不允许",
		nil,
	}).Render(w)
}
func Result(w http.ResponseWriter, message string, data interface{}, code int) {
	(&response{
		code,
		message,
		data,
	}).Render(w)
}

func ExpireAt(w http.ResponseWriter, t time.Time) {
	w.Header().Set("Expires", t.Format(time.RFC1123))
}

func Expire(w http.ResponseWriter, t time.Duration) {
	w.Header().Set("Expires", time.Now().Add(t).Format(time.RFC1123))
}
